package com.polaris.live.ui.message

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.UriUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.lxj.xpopup.XPopup
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.ext.dp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.util.LogExt
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.ActivityUploadGreetBinding
import com.polaris.live.dialog.common.ConfirmCanalDetailDialog
import com.polaris.live.interface_bag.S3UploadCallback
import com.polaris.live.popup.SelectImagePopup
import com.polaris.live.popup.SelectImagePopup.Companion.CAMERA
import com.polaris.live.resp.go_resp.UploadGreetBean
import com.polaris.live.translation.R
import com.polaris.live.utils.CropUtils
import com.polaris.live.utils.getIntOrString
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.image.normal
import com.polaris.live.viewmodel.MessageGreetViewModel
import com.yalantis.ucrop.UCrop

/**
 * MessageUploadGreetActivity
 * 上传打招呼模板
 *
 * @author Created by 长空 on 2023/10/25/013 11:50
 */
class MessageUploadGreetActivity :
    BaseVbActivity<MessageGreetViewModel, ActivityUploadGreetBinding>() {

    private var imagePath = ""

    private val id by lazy { intent.getIntOrString("id", 0) }
    private val photoUrl by lazy { intent.getStringExtra("photoUrl") ?: "" }
    private val content by lazy { intent.getStringExtra("content") ?: "" }
    private val type by lazy { intent.getIntOrString("type", 0) }

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        when (type) {
            0 -> {//审核中
                Glide.with(this)
                    .load(ImageUtils.imgPath(photoUrl))
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .normal()
                    .into(mBinding.selectImage)
                mBinding.tvRemind.setText(R.string.message_greet_auditing)
                mBinding.etMessage.setText(content)
                mBinding.tvTextLength.text = "${content.length}/140"
                mBinding.csCarmel.isEnabled = false
                mBinding.etMessage.isFocusable = false
                mBinding.etMessage.isFocusableInTouchMode = false
                mBinding.btnCommit.visibility = View.GONE
            }

            1 -> {//审核通过
                Glide.with(this)
                    .load(ImageUtils.imgPath(photoUrl))
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .normal()
                    .into(mBinding.selectImage)
                mBinding.llTitle.visibility = View.GONE
                mBinding.view1.visibility = View.GONE
                mBinding.bvTitle.setRightVisible(true)
                mBinding.etMessage.setText(content)
                mBinding.csCarmel.isEnabled = false
                mBinding.etMessage.isFocusable = false
                mBinding.etMessage.isFocusableInTouchMode = false
                mBinding.tvTextLength.text = "${content.length}/140"
                mBinding.btnCommit.visibility = View.GONE
            }

            2 -> {//审核失败
                Glide.with(this)
                    .load(ImageUtils.imgPath(photoUrl))
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .normal()
                    .into(mBinding.selectImage)
                mBinding.tvRemind.text = getString(R.string.message_greet_upload_failure)
                mBinding.etMessage.setText(content)
                mBinding.tvTextLength.text = "${content.length}/140"
                mBinding.btnCommit.visibility = View.VISIBLE
            }

            3 -> {//上传模板
                mBinding.llTitle.visibility = View.GONE
                mBinding.view1.visibility = View.GONE
                mBinding.btnCommit.visibility = View.VISIBLE
            }
        }

        mBinding.etMessage.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                mBinding.tvTextLength.text = "${s?.length}/140"

            }
        })

        mBinding.bvTitle.setOnRightClientListener {
            XPopup.Builder(this)
                .isDestroyOnDismiss(true)
                .asCustom(
                    ConfirmCanalDetailDialog(
                        this,
                        StringUtils.getString(R.string.warning),
                        StringUtils.getString(R.string.you_sure_detail_say_hi),
                        StringUtils.getString(R.string.cancel),
                        StringUtils.getString(R.string.sure),
                        onCanalCallback = {
                            mViewModel.deleteGreet(id)
                        }, textIsCenter = true
                    )
                ).show()
        }

        mBinding.csCarmel.setOnSingleClickListener {
            XPopup.Builder(this)
                .moveUpToKeyboard(false)
                .isDestroyOnDismiss(true)
                .asCustom(SelectImagePopup(this, onSelectIt = { type ->
                    when (type) {
                        CAMERA -> {
                            CropUtils.startCamera(this, { result ->
                                CropUtils.startCrop(this, result)
                            }, {
                            })
                        }

                        else -> {
                            CropUtils.startAlbum(this, {
                                updatePhoto(it)
                            }, {})
                        }
                    }
                }))
                .show()
        }

        mBinding.btnCommit.setOnSingleClickListener {
            if (type == 3) {
                if (imagePath.isEmpty()) {
                    ToastGravity.showGravity(getString(R.string.message_greet_input_pics))
                    return@setOnSingleClickListener
                } else if (mBinding.etMessage.text.toString().isEmpty()) {
                    ToastGravity.showGravity(getString(R.string.message_greet_input_your_say))
                    return@setOnSingleClickListener
                }
                showLoading(waitTime = 0)

                ImageUtils.s3Upload(
                    imagePath,
                    AppConst.UpLoad.MESSAGE_GREET,
                    callback = object : S3UploadCallback {
                        override fun onSuccess(url: String, size: Pair<Int, Int>?) {
                            mViewModel.uploadGreet(
                                UploadGreetBean(
                                    url,
                                    mBinding.etMessage.text.toString()
                                )
                            )
                        }

                        override fun onFailure(t: Throwable) {
                            LogExt.logE("--net", t)

                            ToastGravity.showGravity(t.message)

                            mViewModel.dismissDialog()
                        }
                    })
            } else {
                if (mBinding.etMessage.text.toString().isEmpty()) {
                    ToastGravity.showGravity(getString(R.string.message_greet_input_your_say))
                    return@setOnSingleClickListener
                }
                showLoading(waitTime = 0)

                if (imagePath.isNotEmpty()) {
                    ImageUtils.s3Upload(
                        imagePath,
                        AppConst.UpLoad.MESSAGE_GREET,
                        callback = object : S3UploadCallback {
                            override fun onSuccess(url: String, size: Pair<Int, Int>?) {
                                mViewModel.putGreet(
                                    UploadGreetBean(
                                        url,
                                        mBinding.etMessage.text.toString(),
                                        id
                                    )
                                )
                            }

                            override fun onFailure(t: Throwable) {
                                LogExt.logE("--net", t)

                                ToastGravity.showGravity(t.message)

                                mViewModel.dismissDialog()
                            }
                        })
                } else {
                    mViewModel.putGreet(
                        UploadGreetBean(
                            photoUrl,
                            mBinding.etMessage.text.toString(),
                            id
                        )
                    )
                }
            }
        }

        initObserver()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
            data?.let { result ->
                val file = UriUtils.uri2File(UCrop.getOutput(result))
                file?.let { uploadFile ->
                    updatePhoto(uploadFile.absolutePath)
                }
            }
        } else if (resultCode == RESULT_CANCELED && requestCode == UCrop.REQUEST_CROP) {
            CropUtils.startCamera(this, { result ->
                CropUtils.startCrop(this, result)
            }, {
            })
        }
    }

    private fun updatePhoto(photoUrl: String) {
        imagePath = photoUrl
        Glide.with(this@MessageUploadGreetActivity).load(photoUrl)
            .transform(RoundedCorners(8.dp))
            .skipMemoryCache(true)
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .into(mBinding.selectImage)
    }

    private fun initObserver() {
        mViewModel.uploadGreetListLiveData.observe(this) {
            ToastGravity.showGravity(getString(R.string.message_greet_upload_success))
            finish()
        }
        mViewModel.deleteGreetListLiveData.observe(this) {
            finish()
        }
        mViewModel.putGreetListLiveData.observe(this) {
            ToastGravity.showGravity(getString(R.string.message_greet_upload_success))
            finish()
        }
    }

}